package edu.jd.imagestorage.storage;

import edu.jd.imagestorage.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/storage")
@CrossOrigin
public class StorageAPI {

    private static String FILE_STORE_PATH = "/home/cloud"; //"C:\wx_tempFile"  "/home/cloud"

    @PostMapping("/upload")
    public Result uploadResource(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        //随机数生成
        Random ra =new Random();
        int ran = ra.nextInt(1000)+1;
        String ran_string = String.valueOf(ran);


        //日期时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String name = sdf.format(date);



        String filename = request.getParameter("filename");

        System.out.println("filename: " + filename);

        String[] tempList = filename.split("\\.");
        String suffix = tempList[tempList.length-1];

        String finalPath = FILE_STORE_PATH +"/" + name + ran_string + "." + suffix;
        String finalName = name + ran_string + "." + suffix;

        //String filePath = FILE_STORE_PATH + "/" + filename;

        try {
            InputStream in = file.getInputStream();

            File uploadDir = new File(FILE_STORE_PATH);
            if(!uploadDir.exists()){
                uploadDir.mkdir();
            }
            OutputStream out = new FileOutputStream(FILE_STORE_PATH+"/"+finalName);

            byte[] b = new byte[10240000];//容量为10240000字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();
        }catch(IOException e){
            System.out.println("IO异常，上传文件失败！");
            return Result.fail(200, "上传文件失败！");
        }

        URLDto dto = new URLDto(finalName);

        return Result.success("上传成功！", dto);
    }

    @GetMapping("/download/{filename}")
    public Result downloadResource(@PathVariable String filename, HttpServletResponse response){

        boolean isNotFound = false;
        try{
            //读取文件的输入流
            InputStream in = new FileInputStream(FILE_STORE_PATH+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = response.getOutputStream();

            byte[] b = new byte[102400000];
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();
        }catch (IOException e){
            System.out.println("IO异常，下载文件失败！");
            isNotFound = true;
        }
        return isNotFound ? Result.fail(404, "资源不存在") : Result.success();
    }

    @PostMapping("/upload2")
    public Result upload2(MultipartFile file){

        //随机数生成
        Random ra =new Random();
        int ran = ra.nextInt(1000)+1;
        String ran_string = String.valueOf(ran);


        //日期时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String name = sdf.format(date);

        //String name = UUID.randomUUID().toString();

        String filename = "";

        try{
            InputStream in = file.getInputStream();

            //String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
            String submittedFilename = file.getOriginalFilename();//原始文件名
            String suffix = submittedFilename.substring(submittedFilename.lastIndexOf("."));
            filename = name + ran_string + suffix;
            OutputStream out = new FileOutputStream(FILE_STORE_PATH +"/"+filename);

            byte[] b = new byte[10240000];//容量为10240000字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();
        }catch (IOException e){
            System.out.println("IO异常，上传文件失败！");
            return Result.fail(200, "上传文件失败！");
        }

        URLDto dto = new URLDto(filename);
        return Result.success("上传成功！", dto);
    }
}
